/*================================================================
*   Copyright (C) 2020 Sangfor Ltd. All rights reserved.
*   
*   文件名称：main.cpp
*   创 建 者：Ann
*   创建日期：2020年06月20日
*   描    述：
*
================================================================*/

#include "epoll_et_svr.hpp"

#define CHECK_RET(p) if(p != true){return 0;}

int main()
{
    TcpSvr listen_ts;
    CHECK_RET(listen_ts.CreateSocket());
    CHECK_RET(listen_ts.Bind("0.0.0.0", 19999));
    CHECK_RET(listen_ts.Listen());

    EpollSvr es;
    es.AddFd(listen_ts.Getfd());

    while(1)
    {
        std::vector<TcpSvr> out;
        if(!es.EpollWait(&out))
        {
            continue;
        }

        for(size_t i = 0; i < out.size(); i++)
        {
            if(out[i].Getfd() == listen_ts.Getfd())
            {
                TcpSvr peerts;
                struct sockaddr_in peeraddr;
                listen_ts.Accept(&peeraddr, &peerts);

                printf("Hava a new connection %s : %d\n", inet_ntoa(peeraddr.sin_addr),
                        ntohs(peeraddr.sin_port));

                peerts.SetNonBlock();
                //true的含义是设置为ET模式
                es.AddFd(peerts.Getfd(), true);
            }
            else
            {
                std::string buf;
                bool ret = out[i].RecvNonBlock(&buf);
                if(!ret)
                {
                    es.DeleteFd(out[i].Getfd());
                    out[i].Close();
                    continue;
                }

                printf("recv data is %s\n", buf.c_str());
                buf.clear();
                buf.assign("i am server");
                out[i].SendNonBlock(buf);
            }
        }
    }
    listen_ts.Close();
    return 0;
}
